﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Ku.Common
{
    public static class ImageHelper
    {
        /// <summary>
        /// 将Base64字符串转换为Image对象
        /// </summary>
        /// <param name="base64Str">base64字符串</param>
        /// <returns></returns>
        public static Bitmap Base64StrToImage(string base64Str)
        {
            Bitmap bitmap = null;

            try
            {
                byte[] arr = Convert.FromBase64String(base64Str);
                MemoryStream ms = new MemoryStream(arr);
                Bitmap bmp = new Bitmap(ms);
                ms.Close();
                bitmap = bmp;
            }
            catch (Exception ex)
            {
            }

            return bitmap;
        }

        /// <summary>
        /// 将Base64字符串转换为图片并保存:base64字符串图片为png
        /// </summary>
        /// <param name="value"></param>
        /// <param name="path">保存图片的路径</param>
        public static void ConvertBase64ToImage(this string value, string path)
        {
            string filepath = Path.GetDirectoryName(path);
            // 如果不存在就创建file文件夹  
            if (!Directory.Exists(filepath))
            {
                if (filepath != null) Directory.CreateDirectory(filepath);
            }
            var match = Regex.Match(value, "data:image/png;base64,([\\w\\W]*)$");
            if (match.Success)
            {
                value = match.Groups[1].Value;
            }
            var photoBytes = Convert.FromBase64String(value);
            File.WriteAllBytes(path, photoBytes);
        }

        //图片 转为    base64编码的文本

        public static string ImgToBase64String(Bitmap bmp)

        {
            MemoryStream ms = new MemoryStream();

            bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

            byte[] arr = new byte[ms.Length];

            ms.Position = 0;

            ms.Read(arr, 0, (int)ms.Length);

            ms.Close();

            String strbaser64 = Convert.ToBase64String(arr);



            return strbaser64;

        }
    }
}
